import React, { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Card,
  Input,
  Button,
  Select,
  Typography,
  Space,
  Dropdown,
  Menu,
  message
} from 'antd';
import {
  DownOutlined,
  SyncOutlined,
  CopyOutlined,
  CodeOutlined
} from '@ant-design/icons';
import OpenAI from 'openai';
import promptPlusService from '@/services/prompt-plus';

const { TextArea } = Input;
const { Text } = Typography;

const PromptOptimizer = () => {
  const [originalPrompt, setOriginalPrompt] = useState('');
  const [optimizedPrompt, setOptimizedPrompt] = useState('');
  const [testContent, setTestContent] = useState('');
  const [originalResult, setOriginalResult] = useState('测试结果将显示在这里...');
  const [optimizedResult, setOptimizedResult] = useState('测试结果将显示在这里...');
  const [showOptimizedResult, setShowOptimizedResult] = useState(true);
  const [viewMode, setViewMode] = useState('markdown');
  const [models, setModels] = useState<API.Model[]>([]);
  const [templates, setTemplates] = useState<API.Template[]>([]);
  const [selectedModel, setSelectedModel] = useState('');
  const [selectedTemplate, setSelectedTemplate] = useState('');
  const [isOptimizing, setIsOptimizing] = useState(false);
  const [isComparing, setIsComparing] = useState(false);
  const [abortController, setAbortController] = useState<AbortController | null>(null);
  const [loading, setLoading] = useState({
    models: false,
    templates: false
  });

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(prev => ({ ...prev, models: true }));
        const modelsRes = await promptPlusService.model.getAllModels();
        setModels(modelsRes);
        if (modelsRes.length > 0) {
          setSelectedModel(modelsRes[0].identifier);
        }

        setLoading(prev => ({ ...prev, templates: true }));
        const templatesRes = await promptPlusService.template.getAllTemplates();
        setTemplates(templatesRes);
        if (templatesRes.length > 0) {
          setSelectedTemplate(templatesRes[0].name);
        }
      } catch (error) {
        message.error('加载数据失败');
        console.error('Error loading data:', error);
      } finally {
        setLoading({ models: false, templates: false });
      }
    };

    fetchData();

    return () => {
      if (abortController) {
        abortController.abort();
      }
    };
  }, []);

  const handleOptimize = async () => {
    if (!originalPrompt) {
      message.warning('请输入需要优化的提示词');
      return;
    }

    setIsOptimizing(true);
    setOptimizedPrompt('优化中...');

    try {
      const controller = new AbortController();
      setAbortController(controller);

      const model = models.find(m => m.identifier === selectedModel);
      if (!model) {
        throw new Error('未找到选中的模型');
      }

      const template = templates.find(t => t.name === selectedTemplate);
      if (!template) {
        throw new Error('未找到选中的优化模板');
      }

      const templateContent = template.content.replace('{prompt}', originalPrompt);

      const openai = new OpenAI({
        apiKey: model.apiKey,
        baseURL: model.apiUrl,
        dangerouslyAllowBrowser: true
      });

      const stream = await openai.chat.completions.create({
        model: model.defaultSearch,
        messages: [
          {
            role: 'user',
            content: templateContent
          }
        ],
        temperature: 0.7,
        max_tokens: 2000,
        stream: true
      }, {
        signal: controller.signal
      });

      let fullResponse = '';
      for await (const chunk of stream) {
        const content = chunk.choices[0]?.delta?.content || '';
        fullResponse += content;
        setOptimizedPrompt(fullResponse);
      }

      message.success('优化成功');
    } catch (error: any) {
      if (error.name !== 'AbortError') {
        console.error('优化失败:', error);
        message.error(`优化失败: ${error.message}`);
        setOptimizedPrompt('优化失败，请检查配置后重试');
      }
    } finally {
      setIsOptimizing(false);
      setAbortController(null);
    }
  };

  const handleCompare = async () => {
    if (!testContent) {
      message.warning('请输入测试内容');
      return;
    }

    if (!originalPrompt) {
      message.warning('请先输入原始提示词');
      return;
    }

    setIsComparing(true);
    setOriginalResult('生成中...');
    setOptimizedResult('生成中...');

    try {
      const controller = new AbortController();
      setAbortController(controller);

      const model = models.find(m => m.identifier === selectedModel);
      if (!model) {
        throw new Error('未找到选中的模型');
      }

      const openai = new OpenAI({
        apiKey: model.apiKey,
        baseURL: model.apiUrl,
        dangerouslyAllowBrowser: true
      });

      // Original result
      const originalStream = await openai.chat.completions.create({
        model: model.defaultSearch,
        messages: [
          {
            role: 'user',
            content: `${originalPrompt}\n\n${testContent}`
          }
        ],
        temperature: 0.7,
        max_tokens: 2000,
        stream: true
      }, {
        signal: controller.signal
      });

      let originalFullResponse = '';
      for await (const chunk of originalStream) {
        const content = chunk.choices[0]?.delta?.content || '';
        originalFullResponse += content;
        setOriginalResult(originalFullResponse);
      }

      // Optimized result
      if (optimizedPrompt && !optimizedPrompt.includes('优化中') && !optimizedPrompt.includes('优化失败')) {
        const optimizedStream = await openai.chat.completions.create({
          model: model.defaultSearch,
          messages: [
            {
              role: 'user',
              content: `${optimizedPrompt}\n\n${testContent}`
            }
          ],
          temperature: 0.7,
          max_tokens: 2000,
          stream: true
        }, {
          signal: controller.signal
        });

        let optimizedFullResponse = '';
        for await (const chunk of optimizedStream) {
          const content = chunk.choices[0]?.delta?.content || '';
          optimizedFullResponse += content;
          setOptimizedResult(optimizedFullResponse);
        }
      } else {
        setOptimizedResult('无优化后的提示词可用于对比');
      }

      message.success('对比完成');
    } catch (error: any) {
      if (error.name !== 'AbortError') {
        console.error('对比失败:', error);
        message.error(`对比失败: ${error.message}`);
        setOriginalResult('生成失败，请检查配置');
        setOptimizedResult('生成失败，请检查配置');
      }
    } finally {
      setIsComparing(false);
      setAbortController(null);
    }
  };

  const toggleViewMode = () => {
    setViewMode(viewMode === 'markdown' ? 'plain' : 'markdown');
  };

  const templateMenu = (
    <Menu
      items={templates.map(template => ({
        key: template.id,
        label: template.name,
        onClick: () => setSelectedTemplate(template.name)
      }))}
    />
  );

  return (
    <Row gutter={16} style={{ height: 'calc(-112px + 100vh)' }}>
      {/* Prompt Optimization Column */}
      <Col xs={24} lg={12}>
        <Card
          title="提示词优化"
          bordered
          style={{ height: '100%' }}
          loading={loading.models || loading.templates}
        >
          <div style={{ display: 'flex', flexDirection: 'column', height: 'calc(100% - 56px)' }}>
            {/* Original Prompt Section */}
            <div style={{ marginBottom: 16 }}>
              <Text strong>原始提示词</Text>
              <TextArea
                rows={4}
                placeholder="请输入需要优化的prompt..."
                style={{ marginTop: 8 }}
                value={originalPrompt}
                onChange={(e) => setOriginalPrompt(e.target.value)}
              />
            </div>

            {/* Optimization Controls */}
            <div style={{
              display: 'flex',
              gap: 16,
              marginBottom: 16,
              width: '100%',
              alignItems: 'flex-end'
            }}>
              <div style={{ flex: 1 }}>
                <Text type="secondary" style={{ display: 'block', marginBottom: 4 }}>
                  <strong>优化模型</strong>
                </Text>
                <Select
                  style={{ width: '100%', height: 40 }}
                  value={selectedModel}
                  onChange={setSelectedModel}
                  options={models.map(model => ({
                    value: model.identifier,
                    label: model.name
                  }))}
                  loading={loading.models}
                />
              </div>

              <div style={{ flex: 1 }}>
                <Text type="secondary" style={{ display: 'block', marginBottom: 8, fontSize: 14 }}>
                  <strong>优化提示词</strong>
                </Text>
                <Dropdown overlay={templateMenu} disabled={loading.templates}>
                  <Button
                    style={{
                      height: 40,
                      width: '100%',
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      padding: '0 16px',
                      fontSize: 14
                    }}
                  >
                    <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {selectedTemplate || (loading.templates ? '加载中...' : '选择模板')}
                    </span>
                    <DownOutlined style={{ fontSize: 12, marginLeft: 8 }} />
                  </Button>
                </Dropdown>
              </div>

              <Button
                type="primary"
                style={{ height: 40, width: 120 }}
                onClick={handleOptimize}
                disabled={!originalPrompt || isOptimizing || !selectedModel || !selectedTemplate}
                loading={isOptimizing}
              >
                开始优化 →
              </Button>
            </div>

            {/* Optimized Prompt Section */}
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 200 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 12 }}>
                <Text strong>优化后的提示词</Text>
                <Space>
                  <Button
                    icon={<SyncOutlined />}
                    onClick={handleOptimize}
                    disabled={!originalPrompt || isOptimizing || !selectedModel || !selectedTemplate}
                  >
                    继续优化
                  </Button>
                  <Button
                    icon={<CopyOutlined />}
                    disabled={!optimizedPrompt || optimizedPrompt.includes('优化中') || optimizedPrompt.includes('优化失败')}
                    onClick={() => {
                      navigator.clipboard.writeText(optimizedPrompt);
                      message.success('已复制到剪贴板');
                    }}
                  >
                    复制
                  </Button>
                </Space>
              </div>
              <TextArea
                placeholder="优化后的提示词将显示在这里..."
                style={{ flex: 1, minHeight: '100%' }}
                value={optimizedPrompt}
                onChange={(e) => setOptimizedPrompt(e.target.value)}
                rows={20}
                autoSize={{ minRows: 20 }}
              />
            </div>
          </div>
        </Card>
      </Col>

      {/* Test Comparison Column */}
      <Col xs={24} lg={12}>
        <Card
          title="测试对比"
          bordered
          style={{ height: '100%' }}
          loading={loading.models}
        >
          <div style={{ display: 'flex', flexDirection: 'column', height: 'calc(100% - 56px)' }}>
            {/* Test Content Section */}
            <div style={{ marginBottom: 16 }}>
              <Text strong>测试内容</Text>
              <TextArea
                rows={4}
                placeholder="请输入要测试的内容..."
                style={{ marginTop: 8, width: '100%' }}
                value={testContent}
                onChange={(e) => setTestContent(e.target.value)}
              />
            </div>

            {/* Comparison Controls */}
            <div style={{
              display: 'flex',
              gap: 16,
              marginBottom: 16,
              width: '100%',
              alignItems: 'flex-end'
            }}>
              <div style={{ flex: 1 }}>
                <Text type="secondary" style={{ display: 'block', marginBottom: 4 }}>
                  模型
                </Text>
                <Select
                  style={{ width: '100%', height: 40 }}
                  value={selectedModel}
                  onChange={setSelectedModel}
                  options={models.map(model => ({
                    value: model.identifier,
                    label: model.name
                  }))}
                  loading={loading.models}
                />
              </div>

              <Button
                danger
                style={{ height: 40, width: 120 }}
                onClick={() => setShowOptimizedResult(!showOptimizedResult)}
              >
                {showOptimizedResult ? '关闭对比' : '开启对比'}
              </Button>

              <Button
                type="primary"
                style={{ height: 40, width: 120 }}
                icon={viewMode === 'markdown' ? <CodeOutlined /> : null}
                onClick={toggleViewMode}
              >
                {viewMode === 'markdown' ? '纯文本' : 'Markdown'}
              </Button>

              <Button
                type="primary"
                style={{ height: 40, flex: 1 }}
                onClick={handleCompare}
                disabled={!testContent || !originalPrompt || isComparing || !selectedModel}
                loading={isComparing}
              >
                开始对比 →
              </Button>
            </div>

            {/* Comparison Results */}
            <div style={{ flex: 1, display: 'flex', flexDirection: 'row', minHeight: 200 }}>
              {/* Original Result */}
              <Card
                title="原始提示词结果"
                bordered
                style={{ flex: 1 }}
                extra={
                  <Button
                    icon={<CopyOutlined />}
                    size="small"
                    onClick={() => {
                      navigator.clipboard.writeText(originalResult);
                      message.success('已复制到剪贴板');
                    }}
                    disabled={originalResult.includes('生成中') || originalResult.includes('生成失败')}
                  >
                    复制
                  </Button>
                }
              >
                <TextArea
                  readOnly
                  style={{
                    flex: 1,
                    height: 410,
                    overflow: 'auto',
                  }}
                  value={originalResult}
                  rows={18}
                />
              </Card>

              {/* Optimized Result */}
              {showOptimizedResult && (
                <Card
                  title="优化后提示词结果"
                  bordered
                  style={{ flex: 1 }}
                  extra={
                    <Button
                      icon={<CopyOutlined />}
                      size="small"
                      onClick={() => {
                        navigator.clipboard.writeText(optimizedResult);
                        message.success('已复制到剪贴板');
                      }}
                      disabled={optimizedResult.includes('生成中') || optimizedResult.includes('生成失败')}
                    >
                      复制
                    </Button>
                  }
                >
                  <TextArea
                    readOnly
                    style={{
                      flex: 1,
                      height: 410,
                      overflow: 'auto',
                    }}
                    value={optimizedResult}
                    rows={18}
                  />
                </Card>
              )}
            </div>
          </div>
        </Card>
      </Col>
    </Row>
  );
};

export default PromptOptimizer;
